﻿/** Common escencials funcions */


var __currentToken = "";
var __currentSession = null;





// config ajax for next calls
function ajaxSetup() {
    $.ajaxSetup({
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {

            toggleLoading(false);
            //$("#logoLoading").removeClass("fa-spin");

            var err = errorThrown

            try {
                var obj = $.parseJSON(jqXHR.responseText);
                if (data.hasOwnProperty("hasError")) {
                    err = obj.error;
                }
            } catch (e) {
            }


            if ($.gritter == undefined)
                alert("Could not contact server " + __apiURL + " " + err);
            else {
                $.gritter.add({
                    title: 'WARNING!',
                    text: "Could not contact server " + __apiURL + " " + err,
                    image: null,
                    sticky: true
                });
            }
        },
        headers: { "token": __currentToken }
    });
}


// call API
function send(url, data, options, callback, callbackError, skipLoading) {
    if (!options)
        options = new Object();

    if (!skipLoading)
        $("#secondLoading").show();

    if (!options.hasOwnProperty("success")) {
        options.success = function (data, textStatus, jqXHR) {

            //console.log(textStatus);
            // in firefox not return as json
            if ((typeof data != "object") && (data != null) && (data != "")) {
                data = $.parseJSON(data);
            }

            if (!skipLoading) {
                toggleLoading(false);
                //$("#mainLoading").hide();
                //$("#secondLoading").hide();
            }

            if (data && data.hasOwnProperty("hasError")) {
                if ($.gritter == undefined)
                    alert(data.error);
                else {
                    $.gritter.add({
                        title: 'WARNING!',
                        text: data.error,
                        image: null,
                        sticky: true,
                        //time: 3000
                    });
                }
                if (callbackError != undefined)
                    callbackError(data.error);

            }
            else {
                if (callback != undefined) {
                    callback(data);
                }
            }
        };
    }
    if (!options.hasOwnProperty("type"))
        options.type = "GET";

    if (data)
        options.data = data;

    $.ajax(__apiURL + url, options);
}